//数据库封装

db = {
  setName:function(dbname){
    $api.setStorage('dbname', dbname);
  },
  getName:function(){
    return $api.getStorage('dbname');
  },
  open:function(dbname){
    sqlite.openDatabaseSync({name: dbname});
    db.setName(dbname);
  },
  exec:function(sql){
    return sqlite.executeSqlSync({
        name: db.getName(),
        sql: sql
    });
  },
  createTableTicket:function(){
    return db.exec('CREATE TABLE IF NOT EXISTS ticket(id INT(10) PRIMARY KEY NOT NULL, code VARCHAR(12) NOT NULL, qrcode VARCHAR(50), name VARCHAR(20) NOT NULL, status TINYINT(2) NOT NULL DEFAULT 1, is_sync TINYINT(2) NOT NULL DEFAULT 0)');
  },
  dropTable:function(tb){
    return sqlite.executeSqlSync({
        name: db.getName(),
        sql: 'DROP TABLE '+tb
    });
  },
  beginTransaction:function(){
    sqlite.transactionSync({
        name: db.getName(),
        operation: 'begin'
    });
  },
  commitTransaction:function(){
    sqlite.transactionSync({
        name: db.getName(),
        operation: 'commit'
    });
  },
  create:function(tb, data){
    var fieldArr = [];
    var valueArr = [];
    for(k in data){
      fieldArr.push(k);
      valueArr.push(data[k]);
    }
    sqlite.selectSqlSync({
        name: db.getName(),
        sql: 'INSERT INTO '+tb+' ('+fieldArr.join(',')+') VALUES ('+valueArr.join(',')+')'
    });
  },
  delete:function(tb, where){
    sqlite.selectSqlSync({
        name: db.getName(),
        sql: 'DELETE FROM '+tb+' WHERE '+where
    });
  },
  update:function(tb, where, data){
    return sqlite.selectSqlSync({
        name: db.getName(),
        sql: 'UPDATE '+tb+' SET '+data+' WHERE '+where
    });
  },
  findOne:function(tablename, con){
    var where = '1=1';
    for(k in con){
      where += ' and ' + k + '=' + con[k];
    }
    var ret = sqlite.selectSqlSync({
        name: db.getName(),
        sql: 'SELECT * FROM '+tablename+' WHERE '+where+' LIMIT 1'
    });
    return (!ret.status || ret.data.length<1)?false:ret.data[0];
  },
  findAll:function(tablename, con){
    var where = '1=1';
    for(k in con){
      where += ' and ' + k + '=' + con[k];
    }
    return sqlite.selectSqlSync({
        name: db.getName(),
        sql: 'SELECT * FROM '+tablename+' WHERE '+where
    });
  },
  findCount:function(tablename, con){
    var where = '1=1';
    for(k in con){
      where += ' and ' + k + '=' + con[k];
    }
    var re = sqlite.selectSqlSync({
        name: db.getName(),
        sql: 'SELECT COUNT(*) AS total FROM '+tablename+' WHERE '+where
    });
    return re.data[0].total;
  }


};
